package br.com.cast.syscast.municipio.paginas;

import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;

import br.com.cast.syscast.HomePage;
import br.com.cast.syscast.excecoes.MunicipioJaCadastrado;
import br.com.cast.syscast.models.Municipio;
import br.com.cast.syscast.models.Pais;
import br.com.cast.syscast.models.Uf;
import br.com.cast.syscast.services.MunicipioService;
import br.com.cast.syscast.services.PaisService;
import br.com.cast.syscast.services.UfService;
import br.com.cast.syscast.util.ComponentUtil;

public class FormMunicipio extends Form<Municipio> {

	private static final long serialVersionUID = 1L;

	@SpringBean
	private UfService ufService;

	@SpringBean
	private PaisService paisService;
	
	@SpringBean
	private MunicipioService municipioService;

	public FormMunicipio(String id) {
		super(id, new CompoundPropertyModel<Municipio>(new Municipio()));

		criaCampoPais();
		
		criaCampoUf();
		
		criaCampoNome();
		
		criaCampoPopulacao();
		
		criaCampoPIB();

		criaLinkCancelar();
	}

	private void criaCampoPIB() {
		add(new RequiredTextField<>("pib"));
	}

	private void criaCampoPopulacao() {
		add(new RequiredTextField<>("populacao"));
	}

	private void criaCampoNome() {
		add(new RequiredTextField<>("nome")
				.add(new StringValidator(0, 50)));
	}

	private void criaCampoPais() {
		IChoiceRenderer<Pais> renderer = new ChoiceRenderer<>("nome");
		add(new DropDownChoice<>(
				"uf.pais", paisService.consultaTodos(), renderer));
	}
	
	private void criaCampoUf() {
		IChoiceRenderer<Uf> renderer = new ChoiceRenderer<>("siglaNome");
		add(new DropDownChoice<>(
				"uf", ufService.consultaTodos(), renderer));
	}

	private void criaLinkCancelar() {
		add(new Link("cancelar") {
			@Override
			public void onClick() {
				redirecionaListar();
			}
		});
	}

	@Override
	protected void onSubmit() {
		Municipio municipio = (Municipio) getDefaultModelObject();

		try {
			municipioService.salvar(municipio);
			HomePage template = redirecionaListar();
			template.success("Registro inserido com sucesso!");
		} catch (MunicipioJaCadastrado e) {
			error(e.getMessage());
		}
	}

	private HomePage redirecionaListar() {
		HomePage template = ComponentUtil.getTemplate(this);
		template.replace(new ListarMunicipio(HomePage.ID_CONTEUDO));
		return template;
	}

}
